package com.sh.secondhand;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.example.zhouwei.library.CustomPopWindow;
import com.sh.adapter.ProductViewFragmentAdapter;
import com.sh.fragment.ProductViewFragment;
import com.sh.struts.GlobalDefine;
import com.sh.utils.CommonStringUtils;
import org.angmarch.views.NiceSpinner;

import java.util.ArrayList;
import java.util.List;

public class PoductForGenreActivity extends AppCompatActivity implements View.OnClickListener {
    private final static String TAG = "PoductForGenreActivity";
    private final static Integer SEARCH_REQUEST_CODE = 1300;
    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private ProductViewFragmentAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private List<ProductViewFragment> list;

    @BindView(R.id.container)
    ViewPager mViewPager;

    @BindView(R.id.sort)
    NiceSpinner niceSpinnerSort;
    @BindView(R.id.distance)
    NiceSpinner niceSpinnerDistance;

    @BindView(R.id.filter)
    LinearLayout filterView;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.search_view)
    TextView searchView;

    CustomPopWindow popWindow;
    private String sort;
    private Integer distance = -1;
    private String title = "";
    private boolean isFreeExpress = false;
    private boolean isAllNew = false;
    private double minPrice = 0;
    private double maxPrice = 0;
    private List<String> sorts;
    private List<String> distances;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poduct_for_genre);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        Intent intent = getIntent();
        String genreName = intent.getStringExtra("genre");
        list = new ArrayList<>();
        // primary sections of the activity.
        list.add(ProductViewFragment.newInstance(0, genreName));
        mSectionsPagerAdapter = new ProductViewFragmentAdapter(getSupportFragmentManager(), list);

        // Set up the ViewPager with the sections adapter.
        mViewPager.setAdapter(mSectionsPagerAdapter);
        initNiceSpinner();
    }

    public void initNiceSpinner() {
        sorts = GlobalDefine.SORT_CONDITION.getCNames();
        distances = GlobalDefine.DISTANCE.getCNames();
        niceSpinnerSort.attachDataSource(sorts);
        niceSpinnerDistance.attachDataSource(distances);
        niceSpinnerDistance.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.i(TAG, "distance position: " + position);
                String data = distances.get(position);//从spinner中获取被选择的数据
                GlobalDefine.DISTANCE distance1 = GlobalDefine.DISTANCE.getObjectByCname(data.trim());
                if (distance1 != null) {
                    distance = distance1.getDistance();
                    if (mSectionsPagerAdapter.getCount() > 0) {
                        ProductViewFragment frame = (ProductViewFragment) mSectionsPagerAdapter.getItem(0);
                        frame.loadDataByFilter(sort, distance, title, isFreeExpress, isAllNew, minPrice, maxPrice);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        niceSpinnerSort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.i(TAG, "sort position: " + position);
                String data = sorts.get(position);//从spinner中获取被选择的数据
                GlobalDefine.SORT_CONDITION condition = GlobalDefine.SORT_CONDITION.getObjectByCname(data.trim());
                if (condition != null) {
                    sort = condition.name();
                    if (mSectionsPagerAdapter.getCount() > 0) {
                        ProductViewFragment frame = (ProductViewFragment) mSectionsPagerAdapter.getItem(0);
                        frame.loadDataByFilter(sort, distance, title, isFreeExpress, isAllNew, minPrice, maxPrice);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }

    @OnClick({R.id.filter, R.id.search_view})
    @Override
    public void onClick(View v) {
        Integer viewId = v.getId();
        switch (viewId) {
            case R.id.filter: {
                View contentView = LayoutInflater.from(this).inflate(R.layout.popup_window, null);
                handleLogic(contentView);
                popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                        .setView(contentView)//显示的布局
                        .create()//创建PopupWindow
                        .showAsDropDown(filterView, 0, 0);//显示PopupWindow
                break;
            }
            case R.id.search_view: {
                Intent search = new Intent(PoductForGenreActivity.this, SearchActivity.class);
                startActivityForResult(search, SEARCH_REQUEST_CODE);
                break;
            }
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SEARCH_REQUEST_CODE) {
                title = data.getStringExtra("title");
                searchView.setText(title);
                ProductViewFragment frame = (ProductViewFragment) mSectionsPagerAdapter.getItem(0);
                frame.loadDataByFilter(sort, distance, title, isFreeExpress, isAllNew, minPrice, maxPrice);
            }
        }
    }

    private void handleLogic(View contentView) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.reset_btn: {
                        ToggleButton express = contentView.findViewById(R.id.free_express);
                        ToggleButton allNew = contentView.findViewById(R.id.all_new);
                        EditText min = contentView.findViewById(R.id.min_price);
                        EditText max = contentView.findViewById(R.id.max_price);
                        express.setChecked(false);
                        allNew.setChecked(false);
                        min.setText("");
                        max.setText("");
                        break;
                    }
                    case R.id.sure_btn: {
                        ToggleButton express = contentView.findViewById(R.id.free_express);
                        ToggleButton allNew = contentView.findViewById(R.id.all_new);
                        EditText min = contentView.findViewById(R.id.min_price);
                        EditText max = contentView.findViewById(R.id.max_price);
                        isFreeExpress = express.isChecked();
                        isAllNew = allNew.isChecked();
                        minPrice = CommonStringUtils.safeDouble(min.getText().toString());
                        maxPrice = CommonStringUtils.safeDouble(max.getText().toString());
//                        Log.d(TAG, "isFreeExpress: " + isFreeExpress + ", isAllNew: " + isAllNew + ", minPrice: " + minPrice + ", maxPrice: " + maxPrice);
                        ProductViewFragment frame = (ProductViewFragment) mSectionsPagerAdapter.getItem(0);
                        frame.loadDataByFilter(sort, distance, title, isFreeExpress, isAllNew, minPrice, maxPrice);
                        if (popWindow != null) {
                            popWindow.dissmiss();
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
        };
        CompoundButton.OnCheckedChangeListener changeListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                buttonView.setBackgroundResource(isChecked ? R.drawable.btn_blue_bg : R.drawable.btn_gray_bg);
            }
        };
        ToggleButton express = contentView.findViewById(R.id.free_express);
        ToggleButton allNew = contentView.findViewById(R.id.all_new);
        EditText min = contentView.findViewById(R.id.min_price);
        EditText max = contentView.findViewById(R.id.max_price);
        contentView.findViewById(R.id.reset_btn).setOnClickListener(listener);
        contentView.findViewById(R.id.sure_btn).setOnClickListener(listener);
        express.setOnCheckedChangeListener(changeListener);
        allNew.setOnCheckedChangeListener(changeListener);
        express.setChecked(isFreeExpress);
        allNew.setChecked(isAllNew);
        min.setText(minPrice == 0 ? "" : CommonStringUtils.safeString(minPrice));
        max.setText(maxPrice == 0 ? "" : CommonStringUtils.safeString(maxPrice));
    }

}
